<script setup lang="ts" name="PermissionTree">
import { ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, Delete, RefreshRight } from '@element-plus/icons-vue'
import type { Permission } from '@/model/user-role-model'
import { getPermissionTree, deletePermission } from '@/request/user-role-api'

const props = defineProps<{
  visible: boolean
}>()

const emit = defineEmits<{
  (e: 'update:visible', visible: boolean): void
  (e: 'edit', permission: Permission): void
  (e: 'refresh'): void
}>()

// 树数据
const treeData = ref<Permission[]>([])
const loading = ref(false)

// 获取权限树
const fetchPermissionTree = async () => {
  loading.value = true
  try {
    const res = await getPermissionTree()
    if (res.code === 0 && res.data) {
      treeData.value = res.data
    } else {
      ElMessage.error(res.errorMsg || '获取权限树失败')
    }
  } catch (error) {
    console.error('获取权限树出错：', error)
    ElMessage.error('获取权限树失败')
  } finally {
    loading.value = false
  }
}

// 关闭弹窗
const closeDialog = () => {
  emit('update:visible', false)
}

// 刷新权限树
const refreshTree = () => {
  fetchPermissionTree()
  emit('refresh')
}

// 编辑权限
const handleEdit = (permission: Permission) => {
  emit('edit', permission)
  closeDialog()
}

// 删除权限
const handleDelete = (permission: Permission) => {
  ElMessageBox.confirm(`确定要删除权限"${permission.name}"吗？删除后将无法恢复，且可能影响关联的角色权限设置。`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deletePermission(permission.id)
      if (res.code === 0) {
        ElMessage.success('删除成功')
        refreshTree()
      } else {
        ElMessage.error(res.errorMsg || '删除失败')
      }
    } catch (error) {
      console.error('删除权限出错：', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 取消删除，不做操作
  })
}

// 监听弹窗显示状态
watch(() => props.visible, (newVal) => {
  if (newVal) {
    fetchPermissionTree()
  }
})
</script>

<template>
  <el-dialog
    title="权限树结构"
    :model-value="visible"
    @update:model-value="(val) => emit('update:visible', val)"
    :close-on-click-modal="false"
    width="700px"
    @closed="closeDialog"
  >
    <div class="flex justify-between mb-4">
      <h3 class="text-lg font-medium">权限层级结构</h3>
      <el-button type="primary" link :icon="RefreshRight" @click="refreshTree">刷新</el-button>
    </div>

    <div class="tree-container border rounded p-4" style="max-height: 500px; overflow-y: auto;">
      <el-tree
        v-loading="loading"
        :data="treeData"
        node-key="id"
        default-expand-all
        :expand-on-click-node="false"
      >
        <template #default="{ node, data }">
          <div class="custom-tree-node flex items-center justify-between w-full">
            <div class="node-info flex items-center">
              <span v-if="data.icon" class="mr-1">
                <el-icon><component :is="data.icon" /></el-icon>
              </span>
              <span class="label">
                {{ data.name }}
                <span v-if="data.url" class="text-gray-500 text-xs ml-2">({{ data.url }})</span>
                <span v-if="data.method" class="text-blue-500 text-xs ml-1">{{ data.method }}</span>
              </span>
            </div>
            <div class="node-actions">
              <el-button 
                type="primary" 
                link 
                :icon="Edit"
                @click.stop="handleEdit(data)"
              >
                编辑
              </el-button>
              <el-button 
                type="danger" 
                link 
                :icon="Delete"
                @click.stop="handleDelete(data)"
              >
                删除
              </el-button>
            </div>
          </div>
        </template>
      </el-tree>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.custom-tree-node {
  width: 100%;
}

.node-info {
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.node-actions {
  visibility: hidden;
  transition: visibility 0s, opacity 0.3s ease;
  opacity: 0;
}

:deep(.el-tree-node:hover) .node-actions {
  visibility: visible;
  opacity: 1;
}

/* 当按钮被hover时，确保其可见性 */
.node-actions:hover {
  visibility: visible !important;
  opacity: 1 !important;
}

/* 当节点内的按钮被hover时，保持节点的hover状态 */
.custom-tree-node:hover .node-actions {
  visibility: visible;
  opacity: 1;
}

:deep(.el-tree-node__content) {
  height: auto !important;
  min-height: 26px;
  padding: 5px 0;
}
</style>
